package com.iogogogo.tenant.config.base;

import com.iogogogo.tenant.config.DataSourceBasedMultiTenantConnectionProviderImpl;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by tao.zeng on 2021/8/8.
 */
public abstract class BaseDao {

    private static final String TENANT_KEY = "tenant";

    private final DataSourceBasedMultiTenantConnectionProviderImpl datasourceProvider;

    public BaseDao(DataSourceBasedMultiTenantConnectionProviderImpl datasourceProvider) {
        this.datasourceProvider = datasourceProvider;
    }


    /**
     * 动态获取jdbcTemplate
     */
    protected JdbcTemplate getJdbcTemplate() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return null;
        }
        HttpServletRequest req = attributes.getRequest();
        String tenant = req.getHeader(TENANT_KEY);
        return StringUtils.hasLength(tenant) ? new JdbcTemplate(datasourceProvider.selectDataSource(tenant)) : null;
    }
}
